package cn.gcjxsc.repository.specs.merchant;

import cn.gcjxsc.common.data.query.merchant.RechargeRecordQuery;
import cn.gcjxsc.entity.merchant.recharge.RechargeRecord;
import cn.gcjxsc.entity.merchant.recharge.RechargeRecord_;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * @author pumbaa
 * @since 1.0
 */
public class RechargeRecordSpec {

    public static Specification<RechargeRecord> buildSpec(final RechargeRecordQuery filter) {
        return new Specification<RechargeRecord>() {
            @Override
            public Predicate toPredicate(Root<RechargeRecord> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
                List<Predicate> predicateList = new ArrayList<>();
                if (filter.getStartTime() != null && filter.getStartTime() > 0) {
                    predicateList.add(cb.greaterThanOrEqualTo(root.get(RechargeRecord_.created), filter.getStartTime()));
                }
                if (filter.getEndTime() != null && filter.getEndTime() > 0) {
                    predicateList.add(cb.lt(root.get(RechargeRecord_.created), filter.getEndTime()));
                }
                if (filter.getMerchantId() != null && filter.getMerchantId() > 0) {
                    predicateList.add(cb.equal(root.get(RechargeRecord_.ownerId), filter.getMerchantId()));
                }

                return cb.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
    }
}
